package org.example.mylogin.interceptors;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.mylogin.utils.BaseContext;
import org.example.mylogin.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private HttpServletRequest request;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.info("token还剩下{}秒",redisTemplate.getExpire("adminLogin:token", TimeUnit.SECONDS));
        //检查redis
        if(!redisTemplate.hasKey("adminLogin:token"))
        {
            throw new RuntimeException("redis里面token不存在");
        }

        Long expire = redisTemplate.getExpire("adminLogin:token", TimeUnit.SECONDS);
        if(expire < 30)
        {
            redisTemplate.expire("adminLogin:token",40,TimeUnit.SECONDS);

        }

        //获取
        Claims claims = jwtUtil.parseJwt(token);
//        String id = claims.getId();
        String id = claims.get("id",String.class);
        log.info("id:{}",id);
        BaseContext.set(id);
        return true;
    }
}
